package com.lwl.blog.web.controller;

import com.lwl.blog.core.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;

@RestController
@RequestMapping("/fileController")
@Slf4j
public class FileController {

    @Value("${blog.uploadPath}")
    private String uploadPath;

    @Value("${blog.defualtPng}")
    private String defualtPng;

    // 文件的上传，并且响应文件的绝对路径。
//    @PostMapping("/upload")
//    public R upload(@RequestParam("pngFile") MultipartFile file) {
//        System.out.println("FileController.upload:" + uploadPath);
//        FileOutputStream ops = null;
//        InputStream inputStream = null;
//        String filePath = uploadPath + file.getOriginalFilename();
//        try {
//            inputStream = file.getInputStream();
//            ops = new FileOutputStream(filePath);
//            IOUtils.copy(inputStream, ops);
//        } catch (IOException e) {
//            e.printStackTrace();
//        } finally {
//            IOUtils.closeQuietly(inputStream);
//            IOUtils.closeQuietly(ops);
//        }
//        return R.ok().put("data", file); // 文件上传成功后响应文件的绝对路径
//    }

    @GetMapping("/showPng")
    @ResponseBody
    public void showPng(String filePath, HttpServletResponse resp) {

        FileInputStream ips = null;
        try {
            try {
                ips = new FileInputStream(filePath); // 从本地找，
            } catch (FileNotFoundException e) {
                ips = new FileInputStream(defualtPng); // 扎到读取默认的
            }
            IOUtils.copy(ips, resp.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(ips);
        }
    }
}
